﻿using System;
using UnityEngine;

namespace ZyGame
{
    class CountDownSchedule : ISchedule
    {
        public int target;
        public int current;
        public int interval;
        public bool isUp;
        public Action<int> callback;
        private bool completed = false;
        private bool isCanceled = false;
        private float lastCheckTime = 0;
        private ScheduleCancelToken cancelToken;

        public CountDownSchedule(int time, int interval, bool isUp, Action<int> action, ScheduleCancelToken cancelToken)
        {
            this.isUp = isUp;
            this.callback = action;
            this.interval = interval;
            this.target = isUp ? time : 0;
            this.current = isUp ? 0 : time;
            this.cancelToken = cancelToken;
            cancelToken.Register(CancelSchedule);
        }

        public bool isCompletion => completed;

        public void Dispose()
        {
            cancelToken.Dispose();
            cancelToken = null; 
            callback = null;
        }

        private void CancelSchedule()
        {
            isCanceled = true;
        }

        public void Execute()
        {
            if (isCanceled)
            {
                return;
            }
            if (callback == null)
            {
                completed = true;
                return;
            }
            if (Time.realtimeSinceStartup - lastCheckTime < interval)
            {
                return;
            }
            lastCheckTime = Time.realtimeSinceStartup;
            if (isUp)
            {
                current += interval;
                callback(current);
                completed = current >= target;
            }
            else
            {
                current -= interval;
                callback(current);
                completed = current <= target;
            }
        }

        public bool HasCanceled()
        {
            return isCanceled;
        }

        public void Restart()
        {

        }
    }
}